#include <vector>
#include <string>
#include <unordered_set>
#include <unordered_map>
#include <algorithm>

using namespace std;

class Solution {
public:

    // 69. x 的平方根
    // https://leetcode.cn/problems/sqrtx/
    int mySqrt(int x) {
        if (x < 1) 
            return 0;
        
        long long left = 0, right = x;
        while (left < right)
        {
            long long mid = left + (right - left + 1) / 2;
            if (mid * mid <= x)
                left = mid;
            else 
                right = mid - 1;
        }
        return left == right ? left : -1;
    }

    // 35. 搜索插入位置
    //  https://leetcode.cn/problems/search-insert-position/
    int searchInsert(vector<int>& nums, int target) {
        if (nums.size() == 0) return 0;
        int left = 0, right = nums.size() - 1;
        while (left < right)
        {
            int mid = left + (right - left) / 2;
            if (nums[mid] < target)
                left = mid + 1;
            else
                right = mid;
        }

        if (target <= nums[left]) return left;
        else return left + 1;
    }

    // 852. 山脉数组的峰顶索引
    // https://leetcode.cn/problems/peak-index-in-a-mountain-array/
    int peakIndexInMountainArray(vector<int>& arr) {
        int left = 0, right = arr.size() - 1;

        while (left < right)
        {
            int mid = left + (right - left + 1) / 2;
            if (arr[mid] > arr[mid - 1])
                left = mid;
            else if (arr[mid] < arr[mid - 1])
                right = mid - 1;
        }
        return left;
    }

    // 162. 寻找峰值
    // https://leetcode.cn/problems/find-peak-element/
    int findPeakElement(vector<int>& nums) {
        int left = 0, right = nums.size() - 1;
        while (left < right)
        {
            int mid = left + (right - left) / 2;
            if (nums[mid] < nums[mid + 1])
                left = mid + 1;
            else if (nums[mid] > nums[mid + 1])
                right = mid;
        }
        return left;
    }
};